
package com.hulk.ratel.web.exceptionhandler;
import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Throwables;


import com.hulk.ratel.common.constant.enums.BussErrCode;

import com.hulk.ratel.common.exception.BaseRteException;


import com.hulk.ratel.common.exception.InternalApiException;
import com.hulk.ratel.common.util.SpringContextHolder;
import com.hulk.ratel.manage.commonutil.ContentUtil;
import com.hulk.ratel.service.dto.HeadReqDTO;
import com.hulk.ratel.service.dto.HeadRespDTO;

import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.ClientAbortException;
import org.joda.time.DateTime;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.ui.Model;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;


/**
 * @author hulk
 */


@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    




    @ExceptionHandler(value = ClientAbortException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public void doErrorHandler(HttpServletRequest req, HttpServletResponse resp, ClientAbortException e) throws Exception {
        processException(req, resp, BussErrCode.E_900013.getErrCode(), BussErrCode.S_500.getErrDesc(), e);
    }
    //调用内部springcloud服务异常
    @ExceptionHandler({MissingServletRequestParameterException.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public void doErrorHandler(HttpServletRequest req, HttpServletResponse resp, MissingServletRequestParameterException e) throws Exception {
        processException(req, resp, BussErrCode.S_500.getErrCode(), BussErrCode.S_500.getErrDesc(), e);
    }

    //调用内部springcloud服务异常
    @ExceptionHandler(InternalApiException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public void doErrorHandler(HttpServletRequest req, HttpServletResponse resp, InternalApiException e) throws Exception {
        processException(req, resp, BussErrCode.S_500.getErrCode(), BussErrCode.E_900013.getErrDesc(), e);
    }

    @ExceptionHandler(value = BaseRteException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public void doErrorHandler(HttpServletRequest req, HttpServletResponse resp, BaseRteException e) throws Exception {
        processException(req, resp, e.getErrorCode(), e.getMessage(), e);
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public void doErrorHandler(HttpServletRequest req, HttpServletResponse resp, Exception e) throws Exception {
        processException(req, resp, BussErrCode.E_999999.getErrCode(), BussErrCode.E_999999.getErrDesc(), e);
    }

    public static  void    processException(HttpServletRequest req, HttpServletResponse resp, int errorCode, String errorMsg, Throwable e) throws IOException {

        String workId = (String) req.getAttribute("workId");
        String txnCode = (String) req.getAttribute("txnCode");
        String partnerNo = (String) req.getAttribute("partnerNo");
        String traceId = (String) req.getAttribute("traceId");
        log.error(" workId:{}, traceId:{}, partnerNo:{}, txnCode:{},  errorCode:{},errorMsg:{},e:{}", new Object[]{
                workId, traceId, partnerNo, txnCode, errorCode, errorMsg, Throwables.getStackTraceAsString(e)});
        String partnerAESKey = (String) req.getAttribute("partnerAESKey");
        String requestHead = (String) req.getAttribute("requestHead");
        HeadReqDTO reqHead =   JSONObject.parseObject(requestHead, HeadReqDTO.class);
        HeadRespDTO respHead = new HeadRespDTO();
        BeanUtil.copyProperties(reqHead, respHead);
        respHead.setTraceId(traceId);
        respHead.setPartnerNo(partnerNo);
        respHead.setTxnCode(txnCode);
        respHead.setWorkId(workId);
        DateTime now = DateTime.now();
        respHead.setRespDate(now.toString("yyyyMMdd"));
        respHead.setRespTime(now.toString("yyyyMMddHHmmss"));
        respHead.setRespCode(errorCode);
        respHead.setRespMsg(errorMsg);
        ContentUtil   contentUtil = SpringContextHolder.getBean("contentUtil");
        String respJson ;
        try {
            respJson = contentUtil.postHandle(respHead, partnerAESKey, partnerNo, workId);
        } catch (Exception e1) {
           log.error("",e1);
            respJson =   JSONObject.toJSONString(respHead);
        }
        resp.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        resp.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        resp.setCharacterEncoding(StandardCharsets.UTF_8.name());
        PrintWriter wr = resp.getWriter();
        wr.write(respJson);
        wr.flush();
        wr.close();
        //return contentUtil.postHandle(respHead,partnerAESKey, partnerNo, workId);
    }

    @ModelAttribute
    public void addAttribute(Model m) {
        log.debug("============应用到所有@RequestMapping注解方法，在其执行之前把返回值放入Model");
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        log.debug("============应用到所有@RequestMapping注解方法，在其执行之前初始化数据绑定器");
    }

}
